package com.example.apiclientsdk.client;


import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.digest.DigestAlgorithm;
import cn.hutool.crypto.digest.Digester;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.example.apiclientsdk.model.User;
import com.example.apiclientsdk.util.SignUtils;


import java.util.HashMap;
import java.util.Map;

/**
 * api接口客户端
 * author xsq
 */
public class XsqClient {
    private String accessKey;
    private String accessSecret;

    public XsqClient(String accessKey, String accessSecret) {
        this.accessKey = accessKey;
        this.accessSecret = accessSecret;
    }

    private Map<String, String> getHeader(String body) {
        Map<String, String> header = new HashMap<>();
        header.put("accessKey", accessKey);
//        不能发送给前端
//        header.put("accessSecret", accessSecret);
        header.put("nonce", RandomUtil.randomNumbers(4));
        header.put("body", body);
        header.put("timestap",String.valueOf(System.currentTimeMillis()/1000));
        header.put("sign", SignUtils.getSign(body, accessSecret) );
        return header;
    }
//    用户参数加密钥
    private String getSign(Map<String,String> hashMap,String secret){
        Digester md5 = new Digester(DigestAlgorithm.SHA256);
        String testStr  = hashMap.toString() +"."+ secret;
// 5393554e94bf0eb6436f240a4fd71282
        String digestHex = md5.digestHex(testStr);
        return digestHex;
    }
    public String getNameByGet(String name) {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("name", name);
        String result3 = HttpUtil.get("http://localhost:8201/api/name/", paramMap);
        System.out.println(result3);
        return result3;
    }

    public String getNameByPost( String name) {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("name", name);
        String result3 = HttpUtil.post("http://localhost:8201/api/name/", paramMap);
        System.out.println(result3);
        return result3;
    }

    public String getUserNameByPost(User user) {
        String json = JSONUtil.toJsonStr(user);
        HttpResponse httpResponse = HttpRequest.post("http://localhost:8201/api/name/user")
                .addHeaders(getHeader(json))
                .body(json)
                .execute();
        System.out.println(httpResponse.getStatus());
        String result2 = httpResponse.body();
        System.out.println(result2);
        return result2;
    }
}
